package tool

import (
	"archive/zip"
	"io"
	"path/filepath"
	"strings"
)

// WriteZipToResponse 将文件内容打包成ZIP并写入HTTP响应
func WriteZipToResponse(writer io.Writer, files map[string]string) error {
	// 创建ZIP写入器
	zipWriter := zip.NewWriter(writer)
	defer zipWriter.Close()

	// 将每个文件添加到ZIP中
	for path, content := range files {
		// 处理路径分隔符，确保在ZIP中使用正斜杠
		zipPath := filepath.ToSlash(path)
		// 如果路径以绝对路径开头，去掉开头的斜杠
		zipPath = strings.TrimPrefix(zipPath, "/")

		// 创建文件
		fileWriter, err := zipWriter.Create(zipPath)
		if err != nil {
			return err
		}

		// 写入文件内容
		_, err = fileWriter.Write([]byte(content))
		if err != nil {
			return err
		}
	}

	return nil
}
